package com.cfc.stage1;

import org.junit.Test;

import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Set;

/**
 * @description:
 *   https://leetcode.cn/problems/remove-duplicates-from-sorted-array/
 * @author: yangxuan10
 * @create: 2024-04-10 10:25
 **/
public class RemoveDuplicates {

    @Test
    public void test1() {

        int [] a = new int[]{1,1,2};
        //用了四种方式来实现了呢
        System.out.println(removeDuplicates(a));
    }

    public int removeDuplicates(int[] nums) {
        int i = 1;
        int top = nums[0];
        for (int j = 1; j < nums.length; j++) {
            if (top != (nums[j])) {
                top = nums[j];
                nums[i] = nums[j];
                i++;
            }
        }
        return i;
    }

    public int removeDuplicates3(int[] nums) {
        int i = 1;
        LinkedList<Integer> linkedList = new LinkedList<>();
        linkedList.add(nums[0]);
        for (int j = 1; j < nums.length; j++) {
            Integer last = linkedList.getLast();
            if (!last.equals(nums[j])) {
                linkedList.add(nums[j]);
                nums[i] = nums[j];
                i++;
            }
        }
        return linkedList.size();
    }

    public int removeDuplicates2(int[] nums) {
        LinkedList<Integer> linkedList = new LinkedList<>();
        linkedList.add(nums[0]);
        for (int j = 1; j < nums.length; j++) {
            Integer last = linkedList.getLast();
            if (!last.equals(nums[j])) {
                linkedList.add(nums[j]);
            }
        }

        if (linkedList.size() == nums.length) {
            return linkedList.size();
        }
        int i = 0;
        for (Integer integer : linkedList) {
            nums[i] = integer;
            i++;
        }
        return linkedList.size();
    }

    public int removeDuplicates1(int[] nums) {
        Set<Integer> set = new LinkedHashSet<>();
        for (int num : nums) {
            set.add(num);
        }
        if (nums.length != set.size()) {
            int i = 0;
            for (Integer integer : set) {
                nums[i] = integer;
                i++;
            }
        }
        return set.size();
    }

}